package service

import (
	"fmt"
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
	"time"
)

type StudentAdminService struct {
}

func (s *StudentAdminService) SelectAllStudents(getStudentByCondition dto.GetAssignStudent) (total int64, allStudents []model.Student, err error) {
	db := initialization.DB.Model(&model.Student{})
	if getStudentByCondition.College != "" {
		//学院
		db.Where("college like ?", "%"+getStudentByCondition.College+"%")
	}
	if getStudentByCondition.Major != "" {
		//专业
		db.Where("major like ?", "%"+getStudentByCondition.Major+"%")
	}
	if getStudentByCondition.Grade != "" {
		//年级
		db.Where("grade like ?", "%"+getStudentByCondition.Grade+"%")
	}
	if getStudentByCondition.Class != "" {
		//班级
		db.Where("class like ?", "%"+getStudentByCondition.Class+"%")
	}
	if getStudentByCondition.Name != "" {
		//学生姓名
		db.Where("name like ?", "%"+getStudentByCondition.Name+"%")
	}
	if getStudentByCondition.StudentNumber != 0 {
		//学号
		db.Where("student_number like ?", "%"+fmt.Sprintf("%v", getStudentByCondition.StudentNumber)+"%")
	}
	if getStudentByCondition.StudentStatus != "" {
		//学生违规状态
		studentStatus := 1 //违规
		if getStudentByCondition.StudentStatus == "正常" {
			studentStatus = 0
		}
		db.Where("student_status = ?", studentStatus)
	}
	if getStudentByCondition.ViolationLockTimeStart != 0 {
		//将时间戳转化为时间
		timestamp := int64(getStudentByCondition.ViolationLockTimeStart)
		//使用time.Unix将时间转化为时间对象
		timeObj := time.Unix(timestamp, 0)
		db.Where("violation_lock_time_start >= ?", timeObj)
	}
	if getStudentByCondition.ViolationLockTimeEnd != 0 {
		timestamp := int64(getStudentByCondition.ViolationLockTimeEnd)
		timeObj := time.Unix(timestamp, 0)
		db.Where("violation_lock_time_end <= ?", timeObj)
	}
	offset := (getStudentByCondition.PageNo - 1) * getStudentByCondition.PageSize //当前页
	err = db.Count(&total).Limit(getStudentByCondition.PageSize).Offset(offset).Find(&allStudents).Error
	return
}

func (s *StudentAdminService) CancelViolationStudentsByIds(ids dto.CancelByIds) (students []model.Student, err error) {
	// 批量更新学生的 status 为 0 1为违规
	if err := initialization.DB.Model(&model.Student{}).Where("id IN (?)", ids.StudentIds).Updates(map[string]interface{}{"student_status": 0, "violation_lock_time_start": nil, "violation_lock_time_end": nil}).Error; err != nil {
		return nil, err
	}
	// 批量查询符合条件的学生
	if err := initialization.DB.Where("id IN (?)", ids.StudentIds).Find(&students).Error; err != nil {
		return nil, err
	}
	return
}
